package com.baibei.product.quotation;

import android.content.Context;
import android.util.Log;
import android.util.SparseArray;

import com.baibei.basic.BasicPresenterImpl;
import com.baibei.ebec.quotation.QuotationManager;
import com.baibei.ebec.quotation.event.IQuotationEvent;
import com.baibei.ebec.sdk.ApiFactory;
import com.baibei.ebec.sdk.ITradeApi;
import com.baibei.model.Area;
import com.baibei.model.BaseHttpResponse;
import com.baibei.model.PercentInfo;
import com.baibei.model.QuotationInfo;
import com.baibei.model.RankingInfo;
import com.baibei.quotation.QuotationFilter;
import com.baibei.sdk.ApiDefaultObserver;
import com.blankj.utilcode.utils.LogUtils;
import com.rae.swift.Rx;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;

/**
 * 排行榜
 * Created by ChenRui on 2017/8/9 0009 17:38.
 */
public class RankingListPresenterImpl extends BasicPresenterImpl<RankingListContract.View> implements RankingListContract.Presenter, IQuotationEvent {

    // 维护一个数据集，做排序用到
    private List<RankingInfo> mRankingInfoList;

    private ITradeApi mTradeApi;
    private SparseArray<QuotationInfo> mQuotations;

    public RankingListPresenterImpl(Context context, RankingListContract.View view) {
        super(context, view);
        mTradeApi = ApiFactory.getInstance().getTradeApi();

        // 注册行情
        QuotationFilter filter = new QuotationFilter(QuotationFilter.ACTION_QUOTATION_PRODUCT);
        QuotationManager.getInstance().register(this, filter);
    }

    @Override
    public void start() {
        super.start();

        createObservable(mTradeApi.getPercent()).subscribe(new ApiDefaultObserver<PercentInfo>() {
            @Override
            protected void onError(String s) {
                mView.onLoadDataFailed(s);
            }

            @Override
            protected void accept(PercentInfo percentInfo) {
                if (mView == null) return;
                mView.onLoadPercentSuccess(percentInfo);
            }
        });
        // 获取区域
        Area area = mView.getArea();
        reOrderBy(createObservable(mTradeApi.getRankingList(area.name())).map(new Function<List<RankingInfo>, List<RankingInfo>>() {
            @Override
            public List<RankingInfo> apply(@NonNull List<RankingInfo> rankingInfos) throws Exception {
                mRankingInfoList = rankingInfos;
                return rankingInfos;
            }
        }));
    }

    @Override
    public void destroy() {
        QuotationManager.getInstance().unregister(this);
        super.destroy();
    }

    protected void reOrderBy(Observable<List<RankingInfo>> observable) {
        // 获取排序字段
        // JAVA 排序接口返回值说明： a跟b比较，如果a>b，返回1为正序-1为倒序

        observable
                .subscribeOn(Schedulers.io())
                // 保持数据源，使用新的集合
                .map(new Function<List<RankingInfo>, List<RankingInfo>>() {
                    @Override
                    public List<RankingInfo> apply(@NonNull List<RankingInfo> list) throws Exception {
                        // 更新行情价格
                        List<RankingInfo> result = new ArrayList<>(list);
                        if (mQuotations == null || mQuotations.size() <= 0) return result;
                        for (RankingInfo item : result) {
                            QuotationInfo quotationInfo = mQuotations.get(Rx.parseInt(item.getProductId()));
                            if (quotationInfo == null) continue;
                            // 更新价格
                            item.setLastPrice(quotationInfo.getMarketPrice());
                        }
                        return result;
                    }
                })
                // 按照到岸时间正序排列
//                .map(new Function<List<RankingInfo>, List<RankingInfo>>() {
//                    @Override
//                    public List<RankingInfo> apply(@NonNull List<RankingInfo> list) throws Exception {
//                        Collections.sort(list, new Comparator<RankingInfo>() {
//                            @Override
//                            public int compare(RankingInfo a, RankingInfo b) {
//                                if (a.getEstimateTime() == b.getEstimateTime()) return 0;
//                                return a.getEstimateTime() > b.getEstimateTime() ? 1 : -1;
//                            }
//                        });
//
//                        return list;
//                    }
//                })
                // 先按价格排序
                .map(new Function<List<RankingInfo>, List<RankingInfo>>() {
                    @Override
                    public List<RankingInfo> apply(@NonNull List<RankingInfo> list) throws Exception {
                        if ("DEFAULT".equalsIgnoreCase(mView.getPriceOrderBy())) {
                            return list;
                        }
                        Collections.sort(list, new Comparator<RankingInfo>() {
                            @Override
                            public int compare(RankingInfo a, RankingInfo b) {
                                // 保持到岸时间相同的情况下进行重新排序
//                                if (a.getEstimateTime() == b.getEstimateTime()) {
                                int value = getCompareValue(mView.getPriceOrderBy());
                                return a.getLastPrice() > b.getLastPrice() ? value : -value;
//                                }
//                                return 0;
                            }
                        });

                        return list;
                    }
                })
                // 再按涨幅排序
                .map(new Function<List<RankingInfo>, List<RankingInfo>>() {
                    @Override
                    public List<RankingInfo> apply(@NonNull List<RankingInfo> list) throws Exception {
                        if ("DEFAULT".equalsIgnoreCase(mView.getRoseOrderBy())) {
                            return list;
                        }
                        Collections.sort(list, new Comparator<RankingInfo>() {
                            @Override
                            public int compare(RankingInfo a, RankingInfo b) {
                                int value = getCompareValue(mView.getRoseOrderBy());
                                return a.getScopePercent() > b.getScopePercent() ? value : -value;
                            }
                        });

                        return list;
                    }
                })
                .map(new Function<List<RankingInfo>, List<RankingInfo>>() {
                    @Override
                    public List<RankingInfo> apply(@NonNull List<RankingInfo> list) throws Exception {
                        if ("DEFAULT".equalsIgnoreCase(mView.getPayPriceOrderBy())){
                            return list;
                        }
                        Collections.sort(list, new Comparator<RankingInfo>() {
                            @Override
                            public int compare(RankingInfo rankingInfo, RankingInfo t1) {
                                int value = getCompareValue(mView.getPayPriceOrderBy());
                                return rankingInfo.getPrice()>t1.getPrice()?value:-value;
                            }
                        });
                        return list;
                    }
                })

                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ApiDefaultObserver<List<RankingInfo>>() {
                    @Override
                    protected void onError(String s) {
                        if (mView != null)
                            mView.onLoadDataFailed(s);
                    }

                    @Override
                    protected void accept(List<RankingInfo> list) {
                        if (mView != null)
                            mView.onLoadDataSuccess(list);
                    }
                });

    }

    private int getCompareValue(String priceOrderBy) {
        if ("AES".equalsIgnoreCase(priceOrderBy)) {
            return 1;
        } else if ("DESC".equalsIgnoreCase(priceOrderBy)) {
            return -1;
        }
        return 0;
    }

    @Override
    public void refresh() {
        if (Rx.isEmpty(mRankingInfoList)) return;
        // 重新排序
        reOrderBy(createObservable(Observable.just(mRankingInfoList)));
    }

    @Override
    @Subscribe
    public void onEvent(SparseArray<QuotationInfo> quotations) {
        if (Rx.isEmpty(mRankingInfoList) || mView == null) return;
        mQuotations = quotations;

        refresh();
    }
}
